<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时聊天演示</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .chat-container {
            border: 1px solid #ddd;
            height: 400px;
            overflow-y: auto;
            padding: 10px;
            margin-bottom: 20px;
        }
        .message {
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
        }
        .message.sent {
            background-color: #e3f2fd;
            text-align: right;
        }
        .message.received {
            background-color: #f5f5f5;
        }
        .input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        .input-group input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .input-group button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .input-group button:hover {
            background-color: #0056b3;
        }
        .status {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 4px;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <h1>实时聊天演示</h1>
    
    <div id="status" class="status disconnected">未连接</div>
    
    <div class="input-group">
        <input type="text" id="openId" placeholder="输入你的OpenID" value="user1">
        <button onclick="connect()">连接</button>
        <button onclick="disconnect()">断开</button>
    </div>
    
    <div class="input-group">
        <input type="text" id="receiverId" placeholder="接收者OpenID" value="user2">
        <input type="text" id="messageInput" placeholder="输入消息" onkeypress="handleKeyPress(event)">
        <button onclick="sendMessage()">发送</button>
    </div>
    
    <div id="chatContainer" class="chat-container"></div>
    
    <div class="input-group">
        <button onclick="getHistory()">获取历史消息</button>
        <button onclick="markAsRead()">标记已读</button>
        <button onclick="recallMessage()">撤回消息</button>
    </div>

    <script>
        let stompClient = null;
        let currentOpenId = null;
        let messageId = null;

        function connect() {
            const openId = document.getElementById('openId').value;
            if (!openId) {
                alert('请输入OpenID');
                return;
            }
            
            currentOpenId = openId;
            
            // 创建SockJS连接
            const socket = new SockJS('/gerenjiankangguanlixitong/ws-chat');
            stompClient = Stomp.over(socket);
            
            // 设置调试信息
            stompClient.debug = function(str) {
                console.log('STOMP: ' + str);
            };
            
            // 连接
            stompClient.connect({}, function(frame) {
                console.log('Connected: ' + frame);
                updateStatus('已连接', 'connected');
                
                // 订阅个人消息队列
                stompClient.subscribe('/user/' + openId + '/queue/messages', function(message) {
                    const chatMessage = JSON.parse(message.body);
                    displayMessage(chatMessage, 'received');
                });
                
                // 订阅广播消息
                stompClient.subscribe('/topic/messages', function(message) {
                    const chatMessage = JSON.parse(message.body);
                    displayMessage(chatMessage, 'received');
                });
                
            }, function(error) {
                console.log('STOMP error: ' + error);
                updateStatus('连接失败', 'disconnected');
            });
        }

        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
                stompClient = null;
            }
            updateStatus('已断开', 'disconnected');
        }

        function sendMessage() {
            const receiverId = document.getElementById('receiverId').value;
            const messageInput = document.getElementById('messageInput');
            const content = messageInput.value;
            
            if (!content) {
                alert('请输入消息内容');
                return;
            }
            
            if (!stompClient || !stompClient.connected) {
                alert('请先连接WebSocket');
                return;
            }
            
            // 创建消息对象
            const message = {
                senderOpenid: currentOpenId,
                receiverOpenid: receiverId,
                content: content,
                messageType: 'text',
                status: 'sent',
                sendTime: new Date().toISOString()
            };
            
            // 发送消息到服务器
            stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(message));
            
            // 显示发送的消息
            displayMessage(message, 'sent');
            
            // 清空输入框
            messageInput.value = '';
        }

        function displayMessage(message, type) {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + type;
            
            const time = new Date(message.sendTime).toLocaleString();
            messageDiv.innerHTML = `
                <div><strong>${message.senderOpenid}</strong> <small>${time}</small></div>
                <div>${message.content}</div>
                <div><small>ID: ${message.id || 'N/A'}</small></div>
            `;
            
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
            
            // 保存消息ID用于撤回
            if (message.id) {
                messageId = message.id;
            }
        }

        function updateStatus(text, className) {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = text;
            statusDiv.className = 'status ' + className;
        }

        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }

        function getHistory() {
            const receiverId = document.getElementById('receiverId').value;
            if (!receiverId) {
                alert('请输入接收者ID');
                return;
            }
            
            fetch(`/gerenjiankangguanlixitong/api/chat/history?senderOpenId=${currentOpenId}&receiverOpenId=${receiverId}&page=1&size=20`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const chatContainer = document.getElementById('chatContainer');
                        chatContainer.innerHTML = '';
                        
                        data.data.forEach(message => {
                            const type = message.senderOpenid === currentOpenId ? 'sent' : 'received';
                            displayMessage(message, type);
                        });
                    } else {
                        alert('获取历史消息失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取历史消息失败');
                });
        }

        function markAsRead() {
            if (!messageId) {
                alert('没有可标记的消息');
                return;
            }
            
            fetch('/gerenjiankangguanlixitong/api/chat/mark-read', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `messageId=${messageId}&readerOpenId=${currentOpenId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('消息已标记为已读');
                } else {
                    alert('标记失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('标记失败');
            });
        }

        function recallMessage() {
            if (!messageId) {
                alert('没有可撤回的消息');
                return;
            }
            
            fetch('/gerenjiankangguanlixitong/api/chat/recall', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `messageId=${messageId}&senderOpenId=${currentOpenId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('消息已撤回');
                } else {
                    alert('撤回失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('撤回失败');
            });
        }

        // 页面加载时自动连接
        window.onload = function() {
            console.log('页面加载完成，可以开始聊天了');
        };
    </script>
</body>
</html>
